//
//  NetworkTools.swift
//  封装swift数据请求框架
//
//  Created by apple on 16/4/19.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import AFNetworking

// MARK: - request方法枚举
enum WEXRequestMethod: String {
    
    case Post = "post"
    case Get = "get"
    
}


class WEXNetworkTools: AFHTTPSessionManager {
    
//    实现单例
    static let sharedTools: WEXNetworkTools = {
        
        let tools = WEXNetworkTools()
        
//        添加数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()

    typealias WEXRequestCallBack = (responseObject: AnyObject?, error: NSError?)->()
    
    
    func upload(urlString: String, parameters: AnyObject?, datas: [String: NSData], finished: WEXRequestCallBack){
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            for (key,value) in datas {
//                拼接二进制数据
                formData.appendPartWithFileData(value, name: key, fileName: "hehe", mimeType: "application/octet-stream")
                
            }
            
            
            }, progress: nil, success: { (_, responseObject) -> Void in
                
                finished(responseObject: responseObject, error: nil)
                
                
            }) { (_, error) -> Void in
                
                
                finished(responseObject: nil, error: error)
                
        }
    }
    
//    重写了request的方法
    func request(method: WEXRequestMethod, urlString: String, parameters: AnyObject?, finished: (responseObject: AnyObject?, error: NSError?)->() ){
        
        
        if method == WEXRequestMethod.Get {
            
            GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
                
//                执行完成的回调
                finished(responseObject: responseObject, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
//                    执行完成的回调
                    finished(responseObject: nil, error: error)
                    
            })
            
        }else {
            
            POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
                
                
                finished(responseObject: responseObject, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    finished(responseObject: nil, error: error)
                    
            })
        }
        
        
    }
    
    
    
   
    
}
